<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover">

    <title>乘法口诀口算练习</title>
    <link rel="stylesheet" href="assets/mini-default.min.css" />
    <!-- <script src="assets/vue.js"></script> -->
    <!-- <script src="assets/vant.min.js"></script> -->
    <script src="assets/axios.min.js"></script>
    <script src="assets/buzz.min.js"></script>
    <script src="assets/store.min.js"></script>
</head>

<body>

    <div id="app" style="display: flex; flex-direction: column; height: 100%;">
        <nav>
            <div style=" text-align: center;margin-bottom: 0px;font-size: large;">乘法口诀口算练习</div>
        </nav>


        <!-- 耗费的时间和答题进度 -->
        <div v-if="currentTime == null"
            style="background-color:black;color:white;padding-top: 8px; text-align:center; font-size:2rem;">
            00:00</div>
        <div v-if="currentTime != null"
            style="background-color:black;color:white;padding-top: 8px; text-align:center; font-size:2rem;">
            {{currentTime }}</div>
        <div style="background-color:black;color:lightgray;padding-bottom:8px;text-align:center; font-size:20px;">
            {{current_exercise_index + 1}}/{{exercises.length}}</div>

        <div v-if="lastResult!=null" style="display: grid; place-content: center; margin-top: 10px; font-size: large;">
            本次练习耗时 {{lastResult}}
        </div>

        <!-- 当前的题目 -->
        <div v-show="exercising" style="display: flex; justify-content: center; margin-top: 10px;">

            <button style="min-width: 60px;" :class="first_info.button_type" @click="">{{
                first_info.show_value
                }}</button>
            <button style="min-width: 30px;" @click="">X</button>
            <button style="min-width: 60px;" :class="second_info.button_type" @click="">{{
                second_info.show_value
                }}</button>
            <button style="min-width: 30px;" @click="">=</button>
            <button style="min-width: 60px;" :class="result_info.button_type" @click="">{{
                result_info.show_value
                }}</button>
        </div>

        <div v-show="exercising"
            style="text-align: center; color: red; margin-top: 10px; margin-bottom: 10px; font-size: 26px;">
            {{err_count}} </div>

        <!-- 键盘 -->
        <div v-show="exercising" style="display: flex; flex-direction: column; flex-grow: 1; ">
            <div style="display: flex; justify-content: center;">
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(1)">1</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(2)">2</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(3)">3</button>
            </div>
            <div style="display: flex; justify-content: center;">
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(4)">4</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(5)">5</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(6)">6</button>

            </div>
            <div style="display: flex; justify-content: center;">
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(7)">7</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(8)">8</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(9)">9</button>
            </div>
            <div style="display: flex; justify-content: center;">
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(0)">0</button>
                <button plain type="danger" style="width: 7rem; height: 4rem;"
                    @click="clear_input_number">Clear</button>
                <button plain type="success" style="width: 7rem; height: 4rem;" @click="click_on_number(0)">0</button>
            </div>
        </div>
        <span v-show="SuccessToastVisible" class="toast">添加成功!</span>
        <Transition>
            <span v-show="FailToastVisible" class="toast" style="background-color: red;">稍后自动提交!</span>
        </Transition>

        <div style="width: 100%; text-align: center; margin-top: 30px;">
            <!-- <button style="width: 100%;" @click="showFailToast">test</button> -->
            <button style="width: 100%;" v-if="!exercising" @click="start_new_exercise">答题</button>
            <a v-if="!exercising" href="/time_line.html" style="margin-top: 20px; width: 100%;"
                class="button">查看答题记录</a>
        </div>
        <div style="text-align: center; color: lightgray; font-size: small;margin-top: 10px;">version:1.2407.1</div>

    </div>
    <script type="module">
        import { createApp, ref, reactive, computed, onMounted } from "/assets/vue.esm-browser.prod.js"
        // const { createApp, ref, reactive, computed, onMounted } = Vue
        // 在 #app 标签下渲染一个按钮组件
        const app = createApp({
            setup() {
                const current_exercise_index = ref(-1)
                const exercising = ref(false)
                const input_cache = ref([])
                const exercises = ref([])
                const currentTime = ref(null);
                const lastResult = ref(null)
                const start_at_time = ref(null)
                const exercise_count = ref(10)
                const timer = ref(0)
                const err_count = ref(0)
                const tap_sound = new buzz.sound("assets/tap.mp3");
                const achive_sound = new buzz.sound("assets/achive_short.mp3");
                const FailToastVisible = ref(false)
                const SuccessToastVisible = ref(false)

                const start_timer = () => {
                    start_at_time.value = new Date()
                    timer.value = setInterval(() => {
                        var now = new Date();

                        // 计算时间差（毫秒）
                        var diffMS = now.getTime() - start_at_time.value.getTime();

                        // 转换为分钟和秒
                        var diffMin = Math.floor(diffMS / 60000).toString().padStart(2, "0");
                        var diffSec = Math.floor((diffMS % 60000) / 1000).toString().padStart(2, "0");

                        // 格式化输出
                        var formattedTime = `${diffMin}:${diffSec}`;

                        // console.log({ formattedTime });
                        currentTime.value = formattedTime
                    }, 1000);
                }
                const start_new_exercise = () => {
                    tap_sound.play()
                    // exercises.value = [
                    //     {
                    //         first: 4, second: 5, result: 100,
                    //         expected: 20,
                    //     },
                    //     {
                    //         first: 100, second: 6, result: 24,
                    //         expected: 4,
                    //     },
                    //     {
                    //         first: 7, second: 100, result: 56,
                    //         expected: 8,
                    //     },
                    // ]
                    generate_exercise_list()
                    exercising.value = true
                    current_exercise_index.value = 0
                    err_count.value = 0
                    lastResult.value = null
                    start_timer()
                }
                const stop_exercise = () => {
                    //计算最终使用的时间
                    var now = new Date();
                    // 计算时间差（毫秒）
                    var diffMS = now.getTime() - start_at_time.value.getTime();
                    // 转换为分钟和秒
                    var diffMin = Math.floor(diffMS / 60000);
                    var diffSec = Math.floor((diffMS % 60000) / 1000);

                    console.log("停止计时")
                    clearInterval(timer.value)

                    exercising.value = false
                    currentTime.value = null
                    current_exercise_index.value = -1
                    exercises.value = []
                    // return
                    //保存结果记录
                    const result = {
                        minute: diffMin, second: diffSec, err_count: err_count.value,
                    }
                    // 转换为分钟和秒
                    lastResult.value = `${diffMin.toString().padStart(2, "0")}:${diffSec.toString().padStart(2, "0")}`;
                    console.log('练习结果：', { result })
                    add_record(result)
                }
                const next_exercise = () => {
                    if (current_exercise_index.value >= exercises.value.length - 1) {
                        console.log('已经是最后一题，停止练习')
                        stop_exercise()
                        return
                    }

                    console.log('跳转到下一题')
                    current_exercise_index.value++
                }
                const click_on_number = (number) => {
                    tap_sound.play()

                    console.log("click_on_number: ", { number })
                    if (current_exercise_index.value > exercises.value.length - 1) {
                        return
                    }
                    input_cache.value.unshift(number)
                    const exercise = exercises.value[current_exercise_index.value]
                    const expected = exercise.expected
                    let input_result = 0
                    for (let index = 0; index < input_cache.value.length; index++) {
                        const element = input_cache.value[index];
                        input_result += element * Math.pow(10, index)
                    }
                    console.log("calculate input number: ", { expected, input_result })
                    if (input_result > expected) {
                        console.log('计算错误，清空输入，重新计算')
                        input_cache.value = []
                        err_count.value++
                        vant.showToast({
                            message: "计算错误",
                            position: 'bottom',
                        });

                    } else if (input_result == expected) {
                        achive_sound.play()

                        console.log('计算正确结果, 转到下一题目')
                        input_cache.value = []
                        next_exercise()
                    }
                }
                const calculate_current_input_result = () => {
                    let input_result = 0
                    for (let index = 0; index < input_cache.value.length; index++) {
                        const element = input_cache.value[index];
                        input_result += element * Math.pow(10, index)
                    }
                    return input_result
                }
                const try_post_record = () => {
                    const result = {
                        minute: 1, second: 12, err_count: 1,
                    }
                    add_record(result)
                }
                const add_record = (result) => {
                    console.log('提交练习结果', { result })
                    // 定义URL
                    const url = '/add_record'

                    axios.post(url, result)
                        .then(response => {
                            console.log(response.data); // 处理响应数据
                            // vant.showNotify({ type: 'success', message: '添加成功' });
                            showSuccessToast('添加成功');
                        })
                        .catch(error => {
                            console.error(error); // 处理错误
                            showFailToast();
                            setTimeout(() => {
                                add_record(result)
                            }, 5000)
                        });
                }

                const first_info = computed(() => {
                    if (exercising == false || current_exercise_index.value < 0) {
                        return { show_value: 0, button_type: "" }
                    }

                    const exercise = exercises.value[current_exercise_index.value]
                    if (exercise) {
                        if (exercise.first >= 100) {
                            return { show_value: calculate_current_input_result(), button_type: "secondary" }
                        } else {
                            return { show_value: exercise.first, button_type: "primary" }
                        }
                    }
                })
                const second_info = computed(() => {
                    if (exercising == false || current_exercise_index.value < 0) {
                        return { show_value: 0, button_type: "" }
                    }
                    const exercise = exercises.value[current_exercise_index.value]
                    if (exercise) {

                        if (exercise.second >= 100) {
                            return { show_value: calculate_current_input_result(), button_type: "secondary" }
                        } else {
                            return { show_value: exercise.second, button_type: "primary" }
                        }
                    }
                })
                const result_info = computed(() => {
                    if (exercising == false || current_exercise_index.value < 0) {
                        return { show_value: 0, button_type: "" }
                    }
                    const exercise = exercises.value[current_exercise_index.value]
                    if (exercise) {
                        if (exercise.result >= 100) {
                            return { show_value: calculate_current_input_result(), button_type: "secondary" }
                        } else {
                            return { show_value: exercise.result, button_type: "primary" }
                        }
                    }
                })
                const clear_input_number = () => {
                    input_cache.value = []
                }
                const generate_random_number = (min, max) => {
                    // return Math.floor(Math.random() * (max - min + 1)) + min
                    return Math.floor(Math.random() * (max - min)) + min
                }

                const generate_exercise_list = () => {
                    exercises.value = []
                    let source = create_exercise_source()
                    console.log(source)
                    const max = exercise_count.value
                    for (let index = 0; index < max; index++) {
                        const random_exercise_index = generate_random_number(0, source.length - 1)
                        const exercise_src = source.splice(random_exercise_index, 1)[0]
                        let exercise_new = {
                            first: exercise_src.first, second: exercise_src.second, result: exercise_src.result,
                            expected: 20,
                        }
                        const random_expected = generate_random_number(0, 3)
                        switch (random_expected) {
                            case 0:
                                exercise_new.expected = exercise_new.first
                                exercise_new.first = 100
                                break;

                            case 1:
                                exercise_new.expected = exercise_new.second
                                exercise_new.second = 100
                                break;

                            case 2:
                                exercise_new.expected = exercise_new.result
                                exercise_new.result = 100
                                break;
                            default:
                                console.error('should be [0, 2]: ', { random_expected })
                                break
                        }
                        exercises.value.push(exercise_new)
                        console.log("new exercise: ", { exercise_new })
                    }

                }
                const create_exercise_source = () => {
                    let source = []
                    for (let first_index = 2; first_index <= 9; first_index++) {
                        for (let second_index = 2; second_index <= 9; second_index++) {
                            let obj = {
                                first: first_index,
                                second: second_index,
                                result: first_index * second_index,
                                picked: false,
                            }
                            source.push(obj)
                        }
                    }
                    return source
                }

                const get_settings = () => {
                    const url = '/settings'

                    axios.get(url)
                        .then(response => {
                            const res = response.data
                            exercise_count.value = res.data.exercise_count
                            // vant.showSuccessToast('添加成功');
                        })
                        .catch(error => {
                            console.error(error); // 处理错误
                            // showFailToast('获取数据失败');
                        });
                }
                const showFailToast = () => {
                    FailToastVisible.value = true
                    setTimeout(() => {
                        FailToastVisible.value = false
                    }, 1000)
                }
                const showSuccessToast = () => {
                    SuccessToastVisible.value = true
                    setTimeout(() => {
                        SuccessToastVisible.value = false
                    }, 1000)
                }
                onMounted(() => {
                    get_settings()
                })
                return {
                    currentTime,
                    current_exercise_index,
                    exercises,
                    exercising,
                    add_record,
                    start_new_exercise,
                    stop_exercise, next_exercise,
                    click_on_number,
                    first_info, second_info, result_info,
                    lastResult,
                    clear_input_number,
                    try_post_record, err_count,
                    FailToastVisible,
                    SuccessToastVisible,
                    showFailToast, showSuccessToast,
                }
            }
        });
        app.mount('#app');

    </script>

    <style>
        .v-enter-active,
        .v-leave-active {
            transition: opacity 0.5s ease;
        }

        .v-enter-from,
        .v-leave-to {
            opacity: 0;
        }
    </style>
</body>

</html>